package org.example.iris.service.impl;

import org.example.iris.mapper.ApplicationMapper;
import org.example.iris.mapper.JobMapper;
import org.example.iris.mapper.StudentMapper;
import org.example.iris.entity.Application;
import org.example.iris.entity.Job;
import org.example.iris.dto.JobInfo;
import org.example.iris.entity.Student;
import org.example.iris.service.JobService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class JobServiceImpl implements JobService {

    @Autowired
    JobMapper jobMapper;

    @Autowired
    ApplicationMapper applicationMapper;

    @Autowired
    StudentMapper studentMapper;

    @Override
    public List<JobInfo> recommendJob() {

        List<JobInfo> jobInfo = jobMapper.recommendJob();
        for (JobInfo job : jobInfo) {
            job.setTag(List.of(job.getRequirement().replace("[", "")
                    .replace("]", "")
                    .replace("'", "")
                    .split(", ")));
        }
        return jobInfo;
    }

    @Override
    public List<JobInfo> selectJob(String keywords, String city) {
        List<JobInfo> jobs = new ArrayList<>();
        jobs = jobMapper.selectJob(keywords, city);
        for (JobInfo job : jobs) {
            job.setTag(List.of(job.getRequirement().replace("[", "")
                    .replace("]", "")
                    .replace("'", "")
                    .split(", ")));
        }
        return jobs;
    }

    @Override
    public void applyJob(Integer userId, Integer jobId, Integer fileId) {
        Student student = studentMapper.findByUserId(userId);
        Job job = jobMapper.findById(jobId);
        Application application = new Application();
        application.setJobId(jobId);
        application.setStudentId(student.getStudentId());
        System.out.println(student.getStudentId());
        application.setCompanyId(job.getCompanyId());
        application.setStatus("pending");
        application.setFileId(fileId);
        applicationMapper.insertApplication(application);
    }

    @Override
    public JobInfo getJobInfoById(Integer jobId) {
         JobInfo jobInfo = jobMapper.getJobInfoById(jobId);
         jobInfo.setTag(List.of(jobInfo.getRequirement().replace("[", "")
                 .replace("]", "")
                 .replace("'", "")
                 .split(", ")));
         return jobInfo;
    }

    @Override
    public boolean publishJob(Job job) {
        // 校验岗位状态
        if (!job.getStatus().equals("published") && !job.getStatus().equals("closed")) {
            return false;
        }

        // 插入岗位信息
        int result = jobMapper.insertJob(job);
        return result > 0;
    }
}
